package com.clb.toolsbox.toolsJPanel;

import com.clb.toolsbox.dto.ToolItem;
import com.intellij.ui.JBColor;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

public class SidebarToolPanel extends JPanel {

    //JSON格式化
    private final Integer TOOLS_ID_JSON_FORMAT = 1;
    //Base64编码/解码
    private final Integer TOOLS_ID_BASE64_ENCODE = 2;
    //时间戳转换
    private final Integer TOOLS_ID_TIMESTAMP_CONVERSION = 3;


    private static final String TOOL_LIST = "TOOL_LIST";
    private static final String DETAIL_PAGE = "DETAIL_PAGE"; // 新增标识符

    private DefaultListModel<ToolItem> listModel; // 当前显示的模型
    private List<ToolItem> allTools;              // 完整的原始数据
    private JList<ToolItem> toolList;
    private JTextField searchField;

    private CardLayout cardLayout;
    private JPanel contentPanel;

    public SidebarToolPanel() {
        setLayout(new BorderLayout());

        // Top Panel: Search Box
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        searchField = new JTextField(20);

        // 初始化搜索框监听
        setupSearchField();

        topPanel.add(new JLabel("搜索:"));
        topPanel.add(searchField);
        add(topPanel, BorderLayout.NORTH);

        // Center Panel: Tool List + Content Switcher
        cardLayout = new CardLayout();
        contentPanel = new JPanel(cardLayout);

        // 工具列表
        listModel = new DefaultListModel<>();
        toolList = new JList<>(listModel);
        toolList.setCellRenderer(new ToolListCellRenderer());
        toolList.setFixedCellHeight(80); // 设置每项高度
        toolList.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0)); // 上下留白
        toolList.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int index = toolList.locationToIndex(e.getPoint());
                if (index >= 0) {
                    ToolItem selectedItem = listModel.getElementAt(index);
                    if (selectedItem != null) {
                        openTool(selectedItem);
                    }
                }
            }
        });

        JScrollPane scrollPane = new JScrollPane(toolList);
        contentPanel.add(scrollPane, TOOL_LIST);

        add(contentPanel, BorderLayout.CENTER);

        // 初始化工具列表
        initializeTools();
    }

    private void setupSearchField() {
        searchField.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                filterTools();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                filterTools();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                filterTools();
            }
        });
    }

    private void initializeTools() {
        allTools = new ArrayList<>();
        allTools.add(new ToolItem(TOOLS_ID_JSON_FORMAT, "JSON 格式化", "美化和格式化 JSON 数据"));
        allTools.add(new ToolItem(TOOLS_ID_BASE64_ENCODE, "Base64 编码/解码", "对字符串进行 Base64 编码或解码"));
        allTools.add(new ToolItem(TOOLS_ID_TIMESTAMP_CONVERSION, "时间戳转换", "将时间戳转换为日期格式"));
        // 可继续添加更多工具...

        // 初始加载全部工具
        updateToolList(allTools);
    }

    private void filterTools() {
        String keyword = searchField.getText().trim().toLowerCase();

        if (keyword.isEmpty()) {
            updateToolList(allTools); // 显示所有工具
            return;
        }

        List<ToolItem> filteredItems = new ArrayList<>();
        for (ToolItem item : allTools) {
            if (item.getName().toLowerCase().contains(keyword) ||
                    item.getDescription().toLowerCase().contains(keyword)) {
                filteredItems.add(item);
            }
        }

        updateToolList(filteredItems);
    }

    private void updateToolList(List<ToolItem> items) {
        listModel.clear();
        for (ToolItem item : items) {
            listModel.addElement(item);
        }
    }

    private void openTool(ToolItem toolItem) {
        ToolsDetailPage detailPage = new ToolsDetailPage();
        detailPage.setToolCallback(() -> cardLayout.show(contentPanel, TOOL_LIST)); // 返回到工具列表
        if (TOOLS_ID_JSON_FORMAT.equals(toolItem.getToolsId())) {
            //JSON 格式化
            detailPage.showTool(toolItem.getName(), () -> new JsonFormatTool()); // 加载 JSON 工具
        } else if (TOOLS_ID_BASE64_ENCODE.equals(toolItem.getToolsId())) {
            //Base64编码/解码
            detailPage.showTool(toolItem.getName(), () -> new Base64Tool());
        } else if (TOOLS_ID_TIMESTAMP_CONVERSION.equals(toolItem.getToolsId())) {
            detailPage.showTool("时间戳转换", () -> new TimestampConvertTool());
        } else {
            JOptionPane.showMessageDialog(this, "功能暂未实现: " + toolItem.getName());
        }
        contentPanel.add(detailPage, DETAIL_PAGE);
        // 切换到详情页
        cardLayout.show(contentPanel, DETAIL_PAGE);
    }

    // Custom renderer to display both name and description
    static class ToolListCellRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            ToolItem item = (ToolItem) value;

            // 内容面板
            JPanel contentPanel = new JPanel(new BorderLayout(10, 0));
            contentPanel.setOpaque(false); // 不遮挡背景
            contentPanel.setBackground(isSelected ? list.getSelectionBackground() : new Color(43, 43, 43));

            // 图标部分
            char iconChar = item.getName().charAt(0);
            JLabel iconLabel = new JLabel(String.valueOf(iconChar));
            iconLabel.setOpaque(true);
            iconLabel.setBackground(JBColor.DARK_GRAY);
            iconLabel.setForeground(JBColor.WHITE);
            iconLabel.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 20)); // 支持中文
            iconLabel.setHorizontalAlignment(SwingConstants.CENTER);
            iconLabel.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
            iconLabel.setPreferredSize(new Dimension(40, 40));

            // 文字区域
            JPanel textPanel = new JPanel();
            textPanel.setLayout(new BoxLayout(textPanel, BoxLayout.Y_AXIS));
            textPanel.setOpaque(false);

            JLabel nameLabel = new JLabel(item.getName());
            nameLabel.setFont(nameLabel.getFont().deriveFont(Font.BOLD, 16f));
            nameLabel.setForeground(JBColor.WHITE);
            nameLabel.setAlignmentX(Component.LEFT_ALIGNMENT);

            JLabel descLabel = new JLabel(item.getDescription());
            descLabel.setFont(descLabel.getFont().deriveFont(12f));
            descLabel.setForeground(JBColor.WHITE);
            descLabel.setAlignmentX(Component.LEFT_ALIGNMENT);

            textPanel.add(nameLabel);
            textPanel.add(descLabel);

            // 按钮
            JButton enterButton = new JButton("进入工具");
            enterButton.setOpaque(false);
            enterButton.setContentAreaFilled(false);
            enterButton.setBorderPainted(false);
            enterButton.setFocusPainted(false);
            enterButton.setForeground(JBColor.WHITE);
            enterButton.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 16));
            enterButton.addActionListener(e -> {
                System.out.println("进入 " + item.getName());
            });

            // 布局组合
            contentPanel.add(iconLabel, BorderLayout.WEST);
            contentPanel.add(textPanel, BorderLayout.CENTER);
            contentPanel.add(enterButton, BorderLayout.EAST);

            // 外层容器：用于设置外边距
            JPanel outerPanel = new JPanel(new BorderLayout());
            outerPanel.setOpaque(false);
            outerPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); // 上右下左 20px 边距
            outerPanel.add(contentPanel, BorderLayout.CENTER);

            // 圆角背景绘制
            JPanel roundedPanel = new JPanel() {
                @Override
                protected void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    Graphics2D g2 = (Graphics2D) g.create();
                    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                    g2.setColor(getBackground());
                    g2.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 15, 15);
                    g2.dispose();
                }
            };
            roundedPanel.setLayout(new BorderLayout());
            roundedPanel.setOpaque(false);
            roundedPanel.setBackground(isSelected ? list.getSelectionBackground() : new Color(43, 43, 43));
            roundedPanel.add(outerPanel, BorderLayout.CENTER);

            return roundedPanel;
        }
    }
}
